#include "FontShader.h"
#include "Texture.h"
#include <d3dx11async.h>

using namespace Graphics;
RTTI_DEFINITIONS(FontShader)

FontShader::FontShader(void)
	:Shader("FontShader",""),
	 mPixelBuffer(NULL)
{
}

FontShader::~FontShader(void)
{
	Deinitialize();
}

bool FontShader::Initialize()
{
	Graphics::D3DDevice* device = GetPlatform()->GetDevice()->As<Graphics::D3DDevice>();
	return InitializeShader(device->GetWindowsSettings().WindowHandle, 
							"..\\..\\assets\\shaders\\font.vs", 
							"..\\..\\assets\\shaders\\font.ps");
}

void FontShader::Deinitialize()
{
	DeinitializeShader();
}

bool FontShader::Render(int indexCount, D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix, D3DXMATRIX projectionMatrix,  Texture* texture, Color color)
{
	Graphics::D3DDevice* device = GetPlatform()->GetDevice()->As<Graphics::D3DDevice>();

	bool result = SetShaderParameters(worldMatrix, viewMatrix, projectionMatrix, texture, color);

	result = RenderShader(device, indexCount);

	return result;
}

bool FontShader::InitializeShader(HWND hwnd, const char* vsFilename,  const char* psFilename)
{
	Graphics::D3DDevice* device = GetPlatform()->GetDevice()->As<Graphics::D3DDevice>();
	if(Shader::InitializeShader(device, hwnd, vsFilename, psFilename))
	{
		// Create the vertex input layout description.
		// This setup needs to match the VertexType stucture in the ModelClass and in the shader.
		D3D11_INPUT_ELEMENT_DESC polygonLayout[2];
		polygonLayout[0].SemanticName = "POSITION";
		polygonLayout[0].SemanticIndex = 0;
		polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
		polygonLayout[0].InputSlot = 0;
		polygonLayout[0].AlignedByteOffset = 0;
		polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
		polygonLayout[0].InstanceDataStepRate = 0;


		polygonLayout[1].SemanticName = "TEXCOORD";
		polygonLayout[1].SemanticIndex = 0;
		polygonLayout[1].Format = DXGI_FORMAT_R32G32_FLOAT;
		polygonLayout[1].InputSlot = 0;
		polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
		polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
		polygonLayout[1].InstanceDataStepRate = 0;

		// Get a count of the elements in the layout.
		unsigned int numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]);

		// Create the vertex input layout.
		HRESULT result = device->GetDevice()->CreateInputLayout(polygonLayout, numElements, mVertexShaderBuffer->GetBufferPointer(), mVertexShaderBuffer->GetBufferSize(), &mLayout);
		CHECK(result);

		// Release the vertex shader buffer and pixel shader buffer since they are no longer needed.
		mVertexShaderBuffer->Release();
		mVertexShaderBuffer = NULL;

		mPixelShaderBuffer->Release();
		mPixelShaderBuffer = NULL;

		// Create a texture sampler state description.
		D3D11_SAMPLER_DESC samplerDesc;
		samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
		samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
		samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
		samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
		samplerDesc.MipLODBias = 0.0f;
		samplerDesc.MaxAnisotropy = 1;
		samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
		samplerDesc.BorderColor[0] = 0;
		samplerDesc.BorderColor[1] = 0;
		samplerDesc.BorderColor[2] = 0;
		samplerDesc.BorderColor[3] = 0;
		samplerDesc.MinLOD = 0;
		samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;

		// Create the texture sampler state.
		result = device->GetDevice()->CreateSamplerState(&samplerDesc, &mSampleState);
		CHECK(result);

		// Setup the description of the dynamic pixel constant buffer that is in the pixel shader.
		D3D11_BUFFER_DESC pixelBufferDesc;
		pixelBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
		pixelBufferDesc.ByteWidth = sizeof(PixelBufferType);
		pixelBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
		pixelBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
		pixelBufferDesc.MiscFlags = 0;
		pixelBufferDesc.StructureByteStride = 0;

		// Create the pixel constant buffer pointer so we can access the pixel shader constant buffer from within this class.
		result = device->GetDevice()->CreateBuffer(&pixelBufferDesc, NULL, &mPixelBuffer);
		CHECK(result);

		return true;
	}
	return false;
}

void FontShader::DeinitializeShader()
{
	if(mPixelBuffer)
	{
		mPixelBuffer->Release();
		mPixelBuffer = NULL;
	}
}

bool FontShader::SetShaderParameters(D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix, D3DXMATRIX projectionMatrix,  Texture* texture, Color color)
{
	HRESULT result;
	D3D11_MAPPED_SUBRESOURCE mappedResource;
	unsigned int bufferNumber;
	PixelBufferType* dataPtr2;

	Graphics::D3DDevice* device = GetPlatform()->GetDevice()->As<Graphics::D3DDevice>();
	if(Shader::SetShaderParameters(device, worldMatrix, viewMatrix, projectionMatrix))
	{
		// Set shader texture resource in the pixel shader.
		if(texture)
		{
			ID3D11ShaderResourceView* d3dTexture = texture->GetResource();
			device->GetDeviceContext()->PSSetShaderResources(0, 1, &d3dTexture);
		}

		// Lock the pixel constant buffer so it can be written to.
		result = device->GetDeviceContext()->Map(mPixelBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
		CHECK(result);

		// Get a pointer to the data in the pixel constant buffer.
		dataPtr2 = (PixelBufferType*)mappedResource.pData;

		// Copy the pixel color into the pixel constant buffer.
		dataPtr2->PixelColor = color.XColor;

		// Unlock the pixel constant buffer.
		device->GetDeviceContext()->Unmap(mPixelBuffer, 0);

		// Set the position of the pixel constant buffer in the pixel shader.
		bufferNumber = 0;

		// Now set the pixel constant buffer in the pixel shader with the updated value.
		device->GetDeviceContext()->PSSetConstantBuffers(bufferNumber, 1, &mPixelBuffer);
		return true;
	}
	return false;
}